package io.mft.dev.base.config;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.yaml.snakeyaml.Yaml;

import io.mft.commons.config.ConfigProvider.CompletedLoadHandler;
import io.mft.commons.config.ConfigProvider.ConfigProvideLoader;
import io.mft.commons.exception.MFTException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public abstract class LocalConfigProvideLoader implements ConfigProvideLoader {
	protected ClassLoader classLoader;
	public LocalConfigProvideLoader(ClassLoader classLoader) {
		this.classLoader=classLoader;
	}
	@Override
	public ClassLoader classLoader() {
		return classLoader;
	}

	@Override
	public CompletedLoadHandler completedLoadHandler() {
		return ConfigProvideLoader.super.completedLoadHandler();
	}
	
	protected Map<String, Object> parseYaml(ClassLoader classLoader,String path) {
		try {
			String locationPattern = "classpath*:"+path;
			PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(new PathMatchingResourcePatternResolver());
			Resource[] resources = resolver.getResources(locationPattern);
			if (resources==null||resources.length==0) {
				throw new MFTException("未加载到配置资源["+locationPattern+"],请检查");
			}
			log.warn("加载配置资源["+locationPattern+"]数量:"+resources.length);
			Map<String, Object> configObjectMap=new HashMap<>();
			for (Resource resource : resources) {
				Yaml yaml = new Yaml();
				InputStream namespaceInputStream=resource.getInputStream();
				Map<String, Object> kv=yaml.load(namespaceInputStream);
				if (kv!=null) {
					configObjectMap.putAll(kv);
					log.warn("加载配置资源["+locationPattern+"]路径["+resource.getURI().toURL().getPath()+"]");
				}else {
					log.warn("加载配置资源["+locationPattern+"]路径["+resource.getURI().toURL().getPath()+"]配置内容为空,请检查是否忽略");
				}
			}
			return configObjectMap;
		} catch (Exception e) {
			throw new MFTException(e);
		}
	}
}
